package com.qcby.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qcby.admin.config.SystemConstants;
import com.qcby.admin.model.SysMenu;
import com.qcby.admin.dao.SysMenuMapper;
import com.qcby.admin.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcby.admin.utils.SecurityUtils;
import com.qcby.admin.vo.MenuTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2024-09-19
 */
@Service("menuService")
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    public List<String> selectPermsByUserId(Long id) {
        //如果是管理员，返回所有的权限
        if(id == 1L){
            LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(SysMenu::getMenuType,SystemConstants.TYPE_MENU,SystemConstants.TYPE_BUTTON);
            wrapper.eq(SysMenu::getStatus, SystemConstants.STATUS_NORMAL);
            List<SysMenu> menus = list(wrapper);
            List<String> perms = menus.stream()
                    .map(SysMenu::getPerms)
                    .collect(Collectors.toList());
            return perms;
        }
//否则返回所具有的权限
        return getBaseMapper().selectPermsByUserId(id);
    }

    @Override
    public List<SysMenu> selectRouterMenuTreeByUserId(Long userId) {
        SysMenuMapper menuMapper = getBaseMapper();
        List<SysMenu> menus = null;
//判断是否是管理员
        if(SecurityUtils.isAdmin()){
//如果是 获取所有符合要求的Menu
            menus = menuMapper.selectAllRouterMenu();
        }else{
//否则 获取当前用户所具有的Menu
            menus = menuMapper.selectRouterMenuTreeByUserId(userId);
        }
//构建tree
//先找出第一层的菜单 然后去找他们的子菜单设置到children属性中
        List<SysMenu> menuTree = builderMenuTree(menus,0L);
        return menuTree;
    }

    @Override
    public List<SysMenu> selectMenuList(SysMenu menu) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        //menuName模糊查询
        queryWrapper.like(StringUtils.hasText(menu.getMenuName()),SysMenu::getMenuName,menu.getMenuName());
        queryWrapper.eq(StringUtils.hasText(menu.getStatus()),SysMenu::getStatus,menu.getStatus());
        //排序 parent_id和order_num
        queryWrapper.orderByAsc(SysMenu::getParentId,SysMenu::getOrderNum);
        List<SysMenu> menus = list(queryWrapper);;
        return menus;
    }

    @Override
    public boolean hasChild(Long menuId) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getParentId,menuId);
        return count(queryWrapper) != 0;
    }

    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        return getBaseMapper().selectMenuListByRoleId(roleId);
    }

    @Override
    public HashMap<String, Object> buildRoleMenuTree(Long roleId) {
        HashMap<String,Object> data = new HashMap<>();
        //查询所有的菜单项
        List<SysMenu> menuList=menuMapper.selectList(null);
        List<MenuTreeVo> menuTreeVos = buildTree(menuList, 0L);
        List<Long> checkedKeyList=menuMapper.findCheckedKeyByRoleId(roleId);
        data.put("menus",menuTreeVos);
        data.put("checkedKeys",checkedKeyList);
        return data;
    }

    private List<MenuTreeVo> buildTree(List<SysMenu> menus, long parentId) {
        List<MenuTreeVo> tree=new ArrayList<>();
        for (SysMenu menu : menus) {
            if(menu.getParentId().equals(parentId)){
                MenuTreeVo menuTreeVo=new MenuTreeVo();
                menuTreeVo.setId(menu.getId());
                menuTreeVo.setLabel(menu.getMenuName());
                menuTreeVo.setChildren(buildTree(menus,menu.getId()));
                tree.add(menuTreeVo);
            }
        }
        return tree;
    }

    private List<SysMenu> builderMenuTree(List<SysMenu> menus, Long parentId) {
        List<SysMenu> menuTree = menus.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .map(menu -> menu.setChildren(getChildren(menu, menus)))
                .collect(Collectors.toList());
        return menuTree;
    }
    /**
     * 获取存入参数的 子Menu集合
     * @param menu
     * @param menus
     * @return
     */
    private List<SysMenu> getChildren(SysMenu menu, List<SysMenu> menus) {
        List<SysMenu> childrenList;
        childrenList = menus.stream()
                .filter(m -> m.getParentId().equals(menu.getId()))
                .map(m->m.setChildren(getChildren(m,menus)))
                .collect(Collectors.toList());
        return childrenList;
    }

    }

